package com.lingrit.provider.job;

import com.lingrit.provider.entity.ColunmModel;
import com.lingrit.provider.entity.CustomSql;
import com.lingrit.provider.service.app.ICustomSqlService;
import com.lingrit.provider.utils.Constant;
import com.lingrit.provider.utils.LogUilts;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

@Component
public class SchedulerTask {
    @Value("${task.readerDBOne}")
    private String readerDBOne;
    @Value("${task.DB_readerOnepsw}")
    private String DB_readerOnepsw;
    @Value("${task.DB_readerOneuser}")
    private String DB_readerOneuser;
    @Value("${task.writeDBOne}")
    private String writeDB;
    @Value("${task.DB_writeOnepsw}")
    private String DB_writepsw;
    @Value("${task.DB_writeOneuser}")
    private String DB_writeuser;
    @Value("${datax.url}")
    private String dataxUrl;
    @Value("${datax.jsonFile}")
    private String jsonFile;
    @Value("${targetDataBase}")
    private String targetDataBase;
    @Value("${custom.extraction}")
    private String extraction;
    private static CustomSql customSql = new CustomSql();
    @Autowired
    private ICustomSqlService iCustomSqlService;

    /**
     * class_name:
     * param:
     * describe: 增量同步OA网络办公系统数据
     * creat_user: ljm
     * creat_date: 2018/6/5
     * creat_time: 14:12
     **/
    @Scheduled(cron = "0 0/5 * * * ?")
    private void processJobSlfh() {
        if (!StringUtils.EMPTY.equals(extraction)) {
            String[] extractionStr = extraction.split(Constant.DELIMITER);
            for (int i = 0; i < extractionStr.length; i++) {
                String tableAndId = extractionStr[i];
                String[] shDocParam = setShParam(tableAndId.split(":")[0], tableAndId.split(":")[1]);
                processCommand(shDocParam);
            }
        }
    }

    private void processCommand(String[] shParam){
        executeCommand("python "+dataxUrl+"/datax/bin/datax.py -p \"-DreaderDB=" + shParam[0] + " -DDB_readerpsw=" + shParam[1] + " " +
                "-DDB_readeruser=" + shParam[2] + " -DDB_writepsw=" + shParam[3] + " -DDB_writeuser=" + shParam[4] + "  -DwriteDB=" + shParam[5] + " " +
                "-DtableName="+shParam[6]+"  -Dcolumn=" + shParam[7] + "  -DsqlWhere="+shParam[8]+"\"  "+jsonFile+"",shParam[6]);
    }

    private String[] setShParam(String tableName,String appointIdColunm) {
        String[] shParam = new String[9];
        customSql.setAppointIdColunm(appointIdColunm);
        customSql.setAppointTable(tableName);
        String idMaxValue = iCustomSqlService.getIdMaxValue(customSql);
        String sqlWhere = StringUtils.EMPTY;
        if (StringUtils.isEmpty(idMaxValue) || idMaxValue != null) {
            sqlWhere = appointIdColunm + "\\>\\'" + idMaxValue + "\\'";
        }
        StringBuilder column = new StringBuilder();
        List<ColunmModel> columnList = iCustomSqlService.getAllColunm(targetDataBase,tableName);
        columnList.forEach(colunmModel -> {
            column.append("\\'" + colunmModel.getColunmName() + "\\',");
        });
        column.deleteCharAt(column.length() - 1);
        shParam[0] = readerDBOne;
        shParam[1] = DB_readerOnepsw;
        shParam[2] = DB_readerOneuser;
        shParam[3] = DB_writepsw;
        shParam[4] = DB_writeuser;
        shParam[5] = writeDB;
        shParam[6] = tableName;
        shParam[7] = column.toString();
        shParam[8] = sqlWhere;
        return shParam;
    }

    private void executeCommand(String commandString, String table){
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String startDate = dateFormat.format(new Date());
        try {
            List<String> command = new ArrayList<>();
            LinkedList<String> logList=new LinkedList<String>();
            command.add("sh");
            command.add("-c");
            command.add(commandString);

            StringBuffer sb=new StringBuffer();
            for(String com:command){
                sb.append(com+" ");
            }
            System.out.println(sb.toString());

            ProcessBuilder sqoopProcessBuilder = new ProcessBuilder(command);
            Process process = sqoopProcessBuilder.start();
            BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = StringUtils.EMPTY;
            while ((line = input.readLine()) != null) {
                System.out.println(line);
                if (StringUtils.isNotEmpty(line.trim())) {
                    logList.add(line);
                }
            }
            String endDate = dateFormat.format(new Date());
            //日志入库
            if (!CollectionUtils.isEmpty(logList)) {
                LogUilts.addLog(logList,startDate,endDate,table);
            }
            input.close();

            int exitValue = process.waitFor();
            if (exitValue != 0) {
                System.out.println(exitValue);
                Exception e = new Exception();
                throw e;
            }else{
                System.out.println("==========successfully executed extract job==========");
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }
}